/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Juego.java
 *
 * Created on Mar 19, 2012, 1:43:45 PM
 */

package blackjack;

import java.awt.Dimension;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

public class Juego extends javax.swing.JFrame {

    DefaultListModel listaCartasHum = new DefaultListModel();
    DefaultListModel listaBancaLogica = new DefaultListModel();

    Mazo mazo = new Mazo();
    JugadorHumano player = new JugadorHumano();
    Banca playerBanca = new Banca();
    boolean esperar = false;

    public Juego(JugadorHumano usuario) {
        initComponents();
        botonOK.setVisible(false);
        labelInfo.setText("Realizá tu apuesta");
        listaJugador.setModel(listaCartasHum);
        listaBanca.setModel(listaBancaLogica);
        
        player = usuario;
        labelSaldoActual.setText(Float.toString(player.getSaldo()));
        txtUsuario.setText(txtUsuario.getText()+" "+player.getNombre());

        repartoInicial();

        Dimension d = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((d.width - this.getWidth())/2,(d.height - this.getHeight())/2);
       
    }

    public String sumarPuntos(DefaultListModel lista){
        int contador=0;
        for(int i=0; i<lista.getSize();i++){
            Carta cart=(Carta) lista.get(i);
            contador=contador+cart.getValorEntero();
            if(cart.getValor().compareTo("A")==0){
                if(contador>21){
                    contador = contador-10;
                }
            }
        }
        return Integer.toString(contador);
    }

    public void limpiarPantalla(){
        txtApuesta.setText("");
        listaCartasHum.clear();//adaptar al nombre de la DEFAULT LIST MODE que le dieron a la lista de jugador humano
        listaBancaLogica.clear();
        txtTotal1.setText("");
        txtTotal2.setText("");
        labelInfo.setText("Realiza tu apuesta");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDesktopPane1 = new javax.swing.JDesktopPane();
        jInternalFrame1 = new javax.swing.JInternalFrame();
        botonPlantarse = new javax.swing.JButton();
        botonPedirCarta = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        listaJugador = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtTotal2 = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        listaBanca = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtTotal1 = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        txtApuesta = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        botonApostar = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        lableApostado = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        labelSaldoActual = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        labelInfo = new javax.swing.JLabel();
        botonOK = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jInternalFrame1.setVisible(true);

        botonPlantarse.setText("Plantarse");
        botonPlantarse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonPlantarseActionPerformed(evt);
            }
        });

        botonPedirCarta.setText("Pedir Cartas");
        botonPedirCarta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonPedirCartaActionPerformed(evt);
            }
        });

        listaJugador.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Cartas Jugador" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(listaJugador);

        jLabel1.setText("Tus Cartas");

        jLabel2.setText("Total:");

        jScrollPane2.setViewportView(listaBanca);

        jLabel3.setText("Total:");

        jLabel4.setText("Cartas Compu");

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel5.setText("Apuesta:");

        botonApostar.setText("Apostar");
        botonApostar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonApostarActionPerformed(evt);
            }
        });

        jLabel6.setText("Apostado:");

        lableApostado.setText("0");

        jLabel8.setText("Saldo:");

        labelSaldoActual.setText("0");

        txtUsuario.setText("Usuario:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel5))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap(85, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel8))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lableApostado)
                            .addComponent(labelSaldoActual)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(botonApostar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
                            .addComponent(txtApuesta, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(txtUsuario)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtApuesta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(botonApostar, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(89, 89, 89)
                .addComponent(txtUsuario)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(lableApostado))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelSaldoActual)
                    .addComponent(jLabel8))
                .addContainerGap())
        );

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel7.setText("BlackJack Java");

        labelInfo.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N

        botonOK.setText("OK");
        botonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonOKActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
        jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
        jInternalFrame1Layout.setHorizontalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jInternalFrame1Layout.createSequentialGroup()
                .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jInternalFrame1Layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jInternalFrame1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addComponent(labelInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                        .addComponent(botonOK))
                    .addGroup(jInternalFrame1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(botonPedirCarta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jInternalFrame1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(18, 18, 18)
                                .addComponent(txtTotal1))
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(35, 35, 35)
                        .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(botonPlantarse, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jInternalFrame1Layout.createSequentialGroup()
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtTotal2, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)))))
                .addGap(52, 52, 52))
        );
        jInternalFrame1Layout.setVerticalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jInternalFrame1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(botonOK)
                    .addComponent(labelInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addGap(9, 9, 9)
                .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jInternalFrame1Layout.createSequentialGroup()
                        .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(botonPedirCarta, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(botonPlantarse, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(19, 19, 19)
                        .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(jInternalFrame1Layout.createSequentialGroup()
                                .addComponent(jScrollPane2)
                                .addGap(18, 18, 18)
                                .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel3)
                                    .addComponent(txtTotal2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jInternalFrame1Layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtTotal1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel2))))))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        jInternalFrame1.setBounds(0, 0, 550, 380);
        jDesktopPane1.add(jInternalFrame1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 549, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 379, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonPlantarseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonPlantarseActionPerformed

        botonPedirCarta.setEnabled(false);
        String totalBanca, totalHumano;

        Carta nuevaCarta = playerBanca.pedirCarta(mazo);
        listaBancaLogica.addElement(nuevaCarta);
        totalBanca = sumarPuntos(listaBancaLogica);
        txtTotal2.setText(totalBanca);

        while (Integer.parseInt(totalBanca) < 16) {
            labelInfo.setText("La Banca pide otra carta");

            Carta otraCarta = playerBanca.pedirCarta(mazo);
            listaBancaLogica.addElement(otraCarta);
            totalBanca = sumarPuntos(listaBancaLogica);
            txtTotal2.setText(totalBanca);
        }
        if (Integer.parseInt(totalBanca) > 21) {
            labelInfo.setText("La Banca se paso. Ganaste!");
            botonPlantarse.setEnabled(false);

        } else {
             labelInfo.setText("La banca se planta");

            totalHumano = txtTotal1.getText();
            if (Integer.parseInt(totalBanca) > Integer.parseInt(totalHumano)) {
                 labelInfo.setText(labelInfo.getText()+" Perdiste!");
                botonPlantarse.setEnabled(false);
            } else {
                if (Integer.parseInt(totalBanca) == Integer.parseInt(totalHumano)) {
                    labelInfo.setText(labelInfo.getText()+" Empate!");
                    botonPlantarse.setEnabled(false);
                } else {
                     labelInfo.setText(labelInfo.getText()+" Ganaste!!");
                    botonPlantarse.setEnabled(false);
                }
            }

        }
        //JOptionPane.showMessageDialog(this, "Partida terminada", "BlackJack", JOptionPane.INFORMATION_MESSAGE);
        //actualizar DB
        botonOK.setVisible(true);
        //reiniciarPartida();

    }//GEN-LAST:event_botonPlantarseActionPerformed

    public void esperar (int segundos){
        try {
            Thread.sleep(segundos * 1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Juego.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void botonPedirCartaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonPedirCartaActionPerformed
        Carta nuevaCarta = player.pedirCarta(mazo);
        listaCartasHum.addElement(nuevaCarta);
        txtTotal1.setText(sumarPuntos(listaCartasHum));

        if(Integer.parseInt(txtTotal1.getText()) > 21){ //PERDISTE
            AdminDeDatos.getInstance().actualizarBD(player);
            //JOptionPane.showMessageDialog(this, "Te pasaste!");
            labelInfo.setText("Te pasaste!!");
            botonOK.setVisible(true);
            
            botonApostar.setEnabled(false);
            botonPedirCarta.setEnabled(false);
            //botonPlantarse.setEnabled(false);
        }
    }//GEN-LAST:event_botonPedirCartaActionPerformed

    public void reiniciarPartida() {
        //actualizar DB
        limpiarPantalla();
        mazo = mazo.resetearMazo();
        botonApostar.setEnabled(true);
        botonPedirCarta.setEnabled(true);
        repartoInicial();
    }

    private void repartoInicial() {
        Carta nuevaCarta = player.pedirCarta(mazo);
        listaCartasHum.addElement(nuevaCarta);
        txtTotal1.setText(sumarPuntos(listaCartasHum));

        nuevaCarta = player.pedirCarta(mazo);
        listaCartasHum.addElement(nuevaCarta);
        txtTotal1.setText(sumarPuntos(listaCartasHum));

        if(txtTotal1.getText().compareTo("21") == 0){
            labelInfo.setText("BlackJack!!");
        }

        nuevaCarta = playerBanca.pedirCarta(mazo);
        listaBancaLogica.addElement(nuevaCarta);
        txtTotal2.setText(sumarPuntos(listaBancaLogica));
    }

    private void botonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonOKActionPerformed
        reiniciarPartida();
        
        labelInfo.setText("Realizá tu apuesta");
        botonOK.setVisible(false);
        
        botonPlantarse.setEnabled(true);
    }//GEN-LAST:event_botonOKActionPerformed

    private void botonApostarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonApostarActionPerformed
       
    }//GEN-LAST:event_botonApostarActionPerformed

    /**
    * @param args the command line arguments
    */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new Juego().setVisible(true);
//            }
//        });
//    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonApostar;
    private javax.swing.JButton botonOK;
    private javax.swing.JButton botonPedirCarta;
    private javax.swing.JButton botonPlantarse;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel labelInfo;
    private javax.swing.JLabel labelSaldoActual;
    private javax.swing.JLabel lableApostado;
    private javax.swing.JList listaBanca;
    private javax.swing.JList listaJugador;
    private javax.swing.JTextField txtApuesta;
    private javax.swing.JTextField txtTotal1;
    private javax.swing.JTextField txtTotal2;
    private javax.swing.JLabel txtUsuario;
    // End of variables declaration//GEN-END:variables

}
